<?php
/**
 * Created by PhpStorm.
 * User: win10
 * Date: 2018/3/22
 * Time: 17:45
 */

namespace frontend\models;

use yii\base\Model;

/**
 * Class SiginupForm
 * @package api\models
 */
class SiginupForm extends Model
{
    public $beizhu;
    public $mobile;
    public $sms_code;
    public $nick_name;
    public $referer;
    public $access_token;

    //注意这里的规则由你自己定义有几个地段哈
    public function rules()
    {
        return [
            [['mobile', 'sms_code', 'nick_name'], 'required'],
            [['mobile', 'sms_code', 'nick_name', 'referer'], 'filter', 'filter' => 'trim'],
            [['mobile'], 'match', 'pattern' => '/^1[3456789]\d{9}/'],
            ['mobile', 'unique', 'targetClass' => '\frontend\models\User', 'message' => '手机号已存在!'],
            ['sms_code', 'string', 'length' => 6],
            ['sms_code', 'validateSmscode'],
            [['nick_name'], 'string', 'min' => 2],
            [['referer', 'beizhu'], 'safe'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mobile' => '手机号',
            'sms_code' => '短信验证码',
            'status' => '状态',
            'nick_name' => '昵称',
        ];
    }

    //注意这个方法里user表的字段
    public function signup()
    {
        if ($this->validate()) {
            $user = new User();
            $user->mobile = $this->mobile;
            $user->nick_name = $this->nick_name;
            $user->referer = $this->referer;
            $user->beizhu = $this->beizhu;
            $user->status = '10';
            $user->ip = \Yii::$app->request->userIP;
            $user->save();
            return $user;
        }
        return null;
    }

    /**
     * 生成维一数
     * @param $num
     * @return bool|string
     */
    public function createInviteCode($num)
    {
        return substr(md5(microtime()), 0, $num);
    }

    /**
     * @param $attribute
     * @param $params
     * @return bool|string
     * 短信验证
     */
    public function validateSmscode($attribute, $params)
    {

        if (!$this->hasErrors() && User::validateSmscode($this->sms_code, $this->mobile)) {
            return true;
        } else {
            $this->addError($attribute, '短信验证码不正确!');
        }
    }
}